package org.birtserver.backend.service.dbinit;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.birtserver.backend.utils.SqlScript;
import org.springframework.beans.factory.annotation.Required;

public class DBInitialization {
  
  private DataSource dataSource;
    
  public void init() throws SQLException, IOException {
    
    Connection connection = null;
    
    try { 
      
      connection = dataSource.getConnection();
      
      //prepare data structure
      List<String> sqlCommands = SqlScript.parse(this.getClass().getResourceAsStream("/create-db.sql"));
      for (String sqlCommand: sqlCommands) {
        try {
          System.out.println("Executing statement:" + sqlCommand);
          connection.createStatement().execute(sqlCommand);
        } catch (SQLException e) {
          System.out.println(e);
        }
      }
      
      System.out.println("Data for junit tests prepared.");
      
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
    }
    
  }
  
  @Required
  public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
  }
  
}
